package org.example.mall.admin.common.es;

import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 创建索引
 *
 * @author hzq
 * @date 2022/1/14 23:02
 */
@Component
public class CreateEsIndexRunner implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<String, RestHighLevelClientService> serviceMap = applicationContext.getBeansOfType(RestHighLevelClientService.class);
        for (Map.Entry<String, RestHighLevelClientService> service : serviceMap.entrySet()) {
            RestHighLevelClientService clientService = service.getValue();
            // 判断索引是否存在
            // 不存在索引则创建索引
            if (!clientService.existsIndex()) {
                clientService.createIndex();
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
